﻿using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace WpfUIUtilities.Behaviors
{
  /// <summary>
  /// Enables the UI element to pass through and not to "swallow" 
  /// the mouse wheel events, which is done e. g. by the ListView controls.
  /// Usage:
  /// <ListView>
  ///   <i:Interaction.Behaviors>
  ///     <behaviors:PassThroughMouseWheelBehavior />
  ///   </i:Interaction.Behaviors>
  /// </ListView>
  /// You need expression blend sdk to be able to reference System.Windows.Interactivity.
  /// </summary>
  public class PassThroughMouseWheelBehavior : Behavior<UIElement>
  {
    /// <summary>
    /// Wird nach dem Anfügen des Verhaltens an das "AssociatedObject" aufgerufen.
    /// </summary>
    /// <remarks>
    /// Setzen Sie dies außer Kraft, um die Funktionalität in das "AssociatedObject" einzubinden.
    /// </remarks>
    protected override void OnAttached()
    {
      base.OnAttached();
      AssociatedObject.PreviewMouseWheel += AssociatedObjectPreviewMouseWheel;
    }

    /// <summary>
    /// Wird aufgerufen, wenn das Verhalten vom "AssociatedObject" getrennt wird. Der Aufruf erfolgt vor dem eigentlichen Trennvorgang.
    /// </summary>
    /// <remarks>
    /// Setzen Sie dies außer Kraft, um die Bindung der Funktionalität zum "AssociatedObject" zu lösen.
    /// </remarks>
    protected override void OnDetaching()
    {
      AssociatedObject.PreviewMouseWheel -= AssociatedObjectPreviewMouseWheel;
      base.OnDetaching();
    }

    /// <summary>
    /// Will be called when the the mouse wheel is moved over the associated element.
    /// </summary>
    /// <param name="sender">Not used.</param>
    /// <param name="e">Used to raise the event again.</param>
    private void AssociatedObjectPreviewMouseWheel(object sender, MouseWheelEventArgs e)
    {
      e.Handled = false;
      AssociatedObject.RaiseEvent(
        new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta) 
        { RoutedEvent = UIElement.MouseWheelEvent }
      );
    }
  }
}
